package com.eslserver.action.group;

import java.io.IOException;
import java.util.Collection;
import java.util.Vector;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eslserver.core.ESLServerPageDispatcher;
import com.eslserver.dao.DAOException;
import com.eslserver.dao.ESLDAO;
import com.eslserver.dao.ESLServerDAOFactory;
import com.eslserver.dao.GroupDAO;
import com.eslserver.to.ESL;

@SuppressWarnings("serial")
public class DeleteGroupAction extends HttpServlet implements
		ESLServerPageDispatcher {
	public static final Logger LOG = LoggerFactory
			.getLogger(DeleteGroupAction.class);

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			ESLDAO eslDAO = ESLServerDAOFactory.getDAOFactory(
					ESLServerDAOFactory.ESLSERVER_DAOFACTORY).getESLDAO();
			GroupDAO groupDAO = ESLServerDAOFactory.getDAOFactory(
					ESLServerDAOFactory.ESLSERVER_DAOFACTORY).getGroupDAO();

			Collection<ESL> esls = new Vector<ESL>();
			String[] selectedCheckboxes = req
					.getParameterValues(PARAM_ALL_SELECTED_CB);

			if (selectedCheckboxes != null) {
				for (String groupID : selectedCheckboxes) {
					groupDAO.deleteGroup(Integer.valueOf(groupID));

					esls = groupDAO.loadGroup(Integer.valueOf(groupID))
							.getEsls();
					for (ESL esl : esls) {
						esl.setGroup(null);
						eslDAO.updateESL(esl);
					}
				}
			}

			RequestDispatcher dispatcher = req
					.getRequestDispatcher(MAIN_DASHBOARD);
			dispatcher.forward(req, resp);
		} catch (DAOException e) {
			LOG.error("error to delete Group", e);
		}
	}
}
